package com.block.datapush.service.apipush;

import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.block.common.model.dto.ThirdInfoDTO;
import com.block.common.model.param.PushApiKeyParam;
import com.block.common.service.IApplicationInfoService;
import com.block.common.service.LogFactory;
import com.block.common.service.merchant.IMerchantThirdBaseInfoService;
import com.block.common.util.AESUtil;
import com.block.datapush.enums.PushStatusEnum;
import com.block.datapush.model.PushQueryParam;
import com.block.datapush.model.dto.NoticeParamDTO;
import com.block.datapush.model.result.ProtocolParamResult;
import com.block.datapush.model.result.PushApiResult;
import com.block.datapush.service.IPushApiService;
import com.block.datapush.service.apipush.utils.XiaoAnFenQiSsqUtil;
import com.block.datapush.service.apipush.utils.XiaoAnFenQiUtil;
import com.block.db.entity.MemberSourceInfo;
import com.block.db.entity.MerchantBaseInfo;
import com.block.db.mapper.MerchantThirdBaseInfoMapper;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * 小安分期 双授权
 */
@Service
public class XiaoAnFenQiSsqApiService implements IPushApiService {

    private static final Logger log = LogFactory.getPushLog();

    @Autowired
    IMerchantThirdBaseInfoService merchantThirdBaseInfoService;
    @Autowired
    IApplicationInfoService applicationInfoService;
    @Autowired
    MerchantThirdBaseInfoMapper merchantThirdBaseInfoMapper;

    @Override
    public PushApiResult checkUser(String orderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) throws Exception {

        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);

        String queryUrl = pushApiKeyParam.getCheckUrl();
        String mobileMd5 = memberSourceInfo.getMobileMd5();
        String nameMd5 = SecureUtil.md5(memberSourceInfo.getRealname()).toLowerCase();

        Map<String, Object> bizMap = new HashMap<>();
        bizMap.put("phoneMd5", mobileMd5);
        bizMap.put("sex", memberSourceInfo.getSex() == 1 ? 1 : 0);
        bizMap.put("nameMd5", nameMd5);
        bizMap.put("age", memberSourceInfo.getAge());
        String city = memberSourceInfo.getCity();
        if (StrUtil.endWith(city, "市")) {
            city = memberSourceInfo.getCity().substring(0, memberSourceInfo.getCity().length() - 1);
        }
        bizMap.put("city", city);
        bizMap.put("socialSecurity", XiaoAnFenQiSsqUtil.getSocialInsurance(memberSourceInfo.getShebao()));
        bizMap.put("accumulationFund", XiaoAnFenQiSsqUtil.getGjj(memberSourceInfo.getGjj()));
        bizMap.put("carProduction", XiaoAnFenQiSsqUtil.getCar(memberSourceInfo.getCar()));
        bizMap.put("estate", XiaoAnFenQiSsqUtil.getHouse(memberSourceInfo.getHouse()));
        bizMap.put("unitSocialSecurity", XiaoAnFenQiSsqUtil.getbaodan(memberSourceInfo.getBaoxian()));
        bizMap.put("sesame", XiaoAnFenQiSsqUtil.getZhimaScore(memberSourceInfo.getZhima()));
        bizMap.put("professionalIdentity", XiaoAnFenQiSsqUtil.getjob(memberSourceInfo.getGongzuo()));
        bizMap.put("customerCreditCard", 1);
        bizMap.put("highestEducation", XiaoAnFenQiSsqUtil.getxueli(memberSourceInfo.getXueli()));
        bizMap.put("monthlyIncome", XiaoAnFenQiSsqUtil.getshouru(memberSourceInfo.getShouru()));
        bizMap.put("customerFormOfPayroll", 1);
        bizMap.put("lengthOfService", 3);
        bizMap.put("loanPurpose", XiaoAnFenQiSsqUtil.getYongtu(memberSourceInfo.getYongtu()));
        bizMap.put("channelSignature", pushApiKeyParam.getApiCode());
        String reqIp = memberSourceInfo.getReqIp();
        if (StringUtils.isNotEmpty(reqIp)){
            bizMap.put("ip", reqIp);
        }else {
            bizMap.put("ip", "127.0.0.1");
        }
        bizMap.put("deviceType", 0);

        String jsonString = JSON.toJSONString(bizMap);
        String ivString = UUID.randomUUID().toString().substring(0, 16);

        String encryptData = AESUtil.encryptBase64(jsonString, pushApiKeyParam.getApiSecret(), ivString);

        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("iv",ivString);
        paramMap.put("data",encryptData);

        log.info("【小安分期下游双授权】撞库开始【queryUrl】{}【bizMap】{}【paramMap】{}", queryUrl, JSON.toJSONString(bizMap), JSON.toJSONString(paramMap));
        String result = HttpUtil.createPost(queryUrl)
                .header("Content-Type", "application/json")
                .body(JSON.toJSONString(paramMap))
                .execute().body();
        JSONObject resultObject = JSON.parseObject(result);

        log.info("【小安分期下游双授权】撞库结束【resultDes】{}", resultObject.toJSONString());

        Integer code = resultObject.getInteger("code");
        String msg = resultObject.getString("msg");

        pushApiResult.setCode(code + "");
        pushApiResult.setMessage(msg);
        pushApiResult.setParamInfo(JSON.toJSONString(bizMap));
        pushApiResult.setResultInfo(result);

        if (code == 200) {
            JSONObject data = resultObject.getJSONObject("data");
            Boolean check = data.getBoolean("check");
            pushApiResult.setCode(code + "|" + check);
            if (check) {
                String serialNo = UUID.randomUUID().toString();
                String productName = data.getString("productName");
                String loanName = data.getString("loanName");
                Integer price = data.getInteger("price");

                JSONArray agreementList = data.getJSONArray("agreementList");
                JSONObject jsonObject = agreementList.getJSONObject(0);
                String name = jsonObject.getString("name");
                String url = jsonObject.getString("url");
                // 撞库成功之后，商户的机构数据存储

                ThirdInfoDTO thirdInfoDTO = new ThirdInfoDTO();
                thirdInfoDTO.setInfoId(Integer.valueOf(pushApiKeyParam.getInfoId()));
                thirdInfoDTO.setInfoName(pushApiKeyParam.getInfoName());
                thirdInfoDTO.setOrderNo(orderNo);
                JSONObject infoObject = new JSONObject();
                infoObject.put("orderNo", serialNo);
                infoObject.put("productId", serialNo);
                infoObject.put("productName", productName);
                infoObject.put("companyName", loanName);
                infoObject.put("companyLogo", "");
                infoObject.put("maxLoanAmount", "200000");
                infoObject.put("maxLoanRate", "36");
                infoObject.put("minLoanRate", "24");
                infoObject.put("businessInfo", pushApiKeyParam.getInfoName());
                JSONArray jsonArray = new JSONArray();
                JSONObject jsonObject1 = new JSONObject();
                jsonObject1.put("protocalName",name);
                jsonObject1.put("protocalUrl",url);
                jsonArray.add(jsonObject1);
                infoObject.put("protocalList", jsonArray);
                thirdInfoDTO.setInfoObject(infoObject);

                boolean save = merchantThirdBaseInfoService.saveThirdInfo(thirdInfoDTO);
                if (save) {
                    pushApiResult.setPushSuccess(true);
                    pushApiResult.setOutOrderNo(serialNo);
                    extJson.put("serialNo", serialNo);
                } else {
                    pushApiResult.setMessage("保存撞库数据失败");
                }
            }
        }
        return pushApiResult;
    }

    @Override
    public PushApiResult queryApprove(String orderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) {
        return null;
    }

    @Override
    public PushApiResult registerUser(String orderNo, String outOrderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) throws Exception {
        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);
        pushApiResult.setOrderNo(orderNo);

        String serialNo = extJson.getString("serialNo");

        String requestUrl = pushApiKeyParam.getRegisterUrl();

        Map<String, Object> bizMap = new HashMap<>();
        bizMap.put("phone", memberSourceInfo.getMobile());
        bizMap.put("sex", memberSourceInfo.getSex() == 1 ? 1 : 0);
        bizMap.put("name", memberSourceInfo.getRealname());
        bizMap.put("age", memberSourceInfo.getAge());
        String city = memberSourceInfo.getCity();
        if (StrUtil.endWith(city, "市")) {
            city = memberSourceInfo.getCity().substring(0, memberSourceInfo.getCity().length() - 1);
        }
        bizMap.put("city", city);
        bizMap.put("socialSecurity", XiaoAnFenQiUtil.getSocialInsurance(memberSourceInfo.getShebao()));
        bizMap.put("accumulationFund", XiaoAnFenQiUtil.getGjj(memberSourceInfo.getGjj()));
        bizMap.put("carProduction", XiaoAnFenQiUtil.getCar(memberSourceInfo.getCar()));
        bizMap.put("estate", XiaoAnFenQiUtil.getHouse(memberSourceInfo.getHouse()));
        bizMap.put("unitSocialSecurity", XiaoAnFenQiUtil.getbaodan(memberSourceInfo.getBaoxian()));
        bizMap.put("sesame", XiaoAnFenQiUtil.getZhimaScore(memberSourceInfo.getZhima()));
        bizMap.put("professionalIdentity", XiaoAnFenQiUtil.getjob(memberSourceInfo.getGongzuo()));
        bizMap.put("customerCreditCard", 1);
        bizMap.put("highestEducation", XiaoAnFenQiUtil.getxueli(memberSourceInfo.getXueli()));
        bizMap.put("monthlyIncome", XiaoAnFenQiUtil.getshouru(memberSourceInfo.getShouru()));
        bizMap.put("customerFormOfPayroll", 1);
        bizMap.put("lengthOfService", 3);
        bizMap.put("loanPurpose", XiaoAnFenQiUtil.getYongtu(memberSourceInfo.getYongtu()));
        bizMap.put("channelSignature", pushApiKeyParam.getApiCode());
        String reqIp = memberSourceInfo.getReqIp();
        if (StringUtils.isNotEmpty(reqIp)){
            bizMap.put("ip", reqIp);
        }else {
            bizMap.put("ip", "127.0.0.1");
        }
        bizMap.put("deviceType", 0);

        String jsonString = JSON.toJSONString(bizMap);
        String ivString = UUID.randomUUID().toString().substring(0, 16);

        String encryptData = AESUtil.encryptBase64(jsonString, pushApiKeyParam.getApiSecret(), ivString);

        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("iv",ivString);
        paramMap.put("data",encryptData);

        log.info("【小安分期下游双授权】导单开始【queryUrl】{}【bizMap】{}【paramMap】{}", requestUrl, JSON.toJSONString(bizMap), JSON.toJSONString(paramMap));
        String result = HttpUtil.createPost(requestUrl)
                .header("Content-Type", "application/json")
                .body(JSON.toJSONString(paramMap))
                .execute().body();

        JSONObject resultObject = JSON.parseObject(result);


        log.info("【小安分期下游双授权】导单结束【result】{}", resultObject.toJSONString());


        Integer code = resultObject.getInteger("code");
        String msg = resultObject.getString("msg");

        pushApiResult.setCode(code + "");
        pushApiResult.setMessage(msg);
        pushApiResult.setParamInfo(JSON.toJSONString(bizMap));
        pushApiResult.setResultInfo(result);

        ThirdInfoDTO thirdInfoDTO = new ThirdInfoDTO();
        thirdInfoDTO.setOrderNo(orderNo );
        thirdInfoDTO.setRetCode(String.valueOf(code));
        thirdInfoDTO.setRetMsg(msg);
        thirdInfoDTO.setResultInfo(result);
        thirdInfoDTO.setStatus("FAILED");

        if (code == 200){
            JSONObject data = resultObject.getJSONObject("data");
            Boolean success = data.getBoolean("success");
            thirdInfoDTO.setRetCode(String.valueOf(code) + "|" + success);
            if (success){
                thirdInfoDTO.setStatus("SUCCESS");
            }
        }
        merchantThirdBaseInfoService.updateThirdInfo(thirdInfoDTO);
        if (code == 200) {
            JSONObject data = resultObject.getJSONObject("data");
            Boolean success = data.getBoolean("success");
            pushApiResult.setCode(code + "|" + success);
            if (success){
                pushApiResult.setPushSuccess(true);
                pushApiResult.setSettleFlag(true);
                pushApiResult.setStatus(PushStatusEnum.SUCCESS.getValue());
                return pushApiResult;
            }
        }
        pushApiResult.setPushSuccess(false);
        pushApiResult.setSettleFlag(false);
        pushApiResult.setStatus(PushStatusEnum.FAILED.getValue());
        return pushApiResult;
    }

    @Override
    public PushApiResult queryResult(PushQueryParam pushQueryParam, PushApiKeyParam pushApiKeyParam, String extJson) {
        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);
        return pushApiResult;
    }

    @Override
    public NoticeParamDTO getNoticeResultParam(String infoId, Map<String, String[]> parameterMap, String paramContent) {
        NoticeParamDTO noticeParamDTO = new NoticeParamDTO();
        return noticeParamDTO;
    }

    @Override
    public JSONObject getNoticeResultReturn(Map<String, String[]> parameterMap, String paramContent, JSONObject extObject) {
        JSONObject jsonObject = new JSONObject();
        return jsonObject;
    }

    @Override
    public ProtocolParamResult getProtocolResult(MerchantBaseInfo merchantBaseInfo, MemberSourceInfo memberSourceInfo) {
        ProtocolParamResult paramResult = new ProtocolParamResult();
        return paramResult;
    }


}
